package com.gaogzhen.aspect;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.gaogzhen.model.RRException;
import com.gaogzhen.utils.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Administrator
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 内部API调用异常
     */
    @ExceptionHandler(value = ApiException.class)
    public R handleApiException(ApiException e) {
        IErrorCode errorCode = e.getErrorCode();
        if (errorCode != null) {
            return R.fail(errorCode);
        }
        return R.fail(e.getMessage());
    }

    /**
     * 方法参数校验失败异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return R.fail(fieldError.getField() + fieldError.getDefaultMessage());
            }
        }
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public R handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return R.fail(fieldError.getField() + fieldError.getDefaultMessage());
            }
        }
        return R.fail(e.getMessage());
    }

    /**
     * 运行时异常
     */
    @ExceptionHandler(value = RRException.class)
    public R handleRRException(RRException e) {
        return R.fail(e.getCode(), e.getMsg());
    }
}
